<template>
	<view>
		
		<!-- 搜索框 -->
		<view class="search-cont">
			<view class="search">
				<input type="text" placeholder-class="inputclass" confirm-type="search"
				focus="true" placeholder="请输入关键字"
				v-model="searchdata"
				@confirm="onKeyInput"/>
			</view>
			<view class="search-code" @click="seArcha()">搜索</view>
		</view>
		
		
		<!-- 搜索历史 -->
		<view class="search-history" v-if="setdataShow">
			<view class="search-title">
				<view>
					搜索历史
				</view>
				<view @click="removeStorage">清空</view>
			</view>
			<view class="menu-block">
				<block v-for="(item,index) in setdata" :key="index">
					<view @click="menubtm(item)">{{item}}</view>
				</block>
			</view>
		</view>
		
		
		<!-- 搜索词云 -->
		<view class="charts-box" v-if="chiyun">
		    <qiun-data-charts 
		      type="word"
		      :opts="opts"
		      :chartData="chartData"
		    />
			<view>搜索词云</view>
		</view>
		
		
		
		 
		<!-- //搜索返回页面 -->
		<view class="divBody" v-if="menus">
		<view class="divMenu">
				<scroll-view scroll-y :scroll-top="scrollTop" :style="{'--height':fixedHeight + 'px'}" class="mescro-uni">
				<!-- <mescroll-uni :fixed="false" ref="mescrollRef" :height="wh"  :down="downOption" :up="upOption"> -->
					
					<view class="divItem"  v-for="(item, index) in acomment" :key="index" >
						<u-image width="172rpx" height="172rpx" :src="item.image" mode="aspectFill" @click="dishDetails(item)">
							<image src="../../static/images/noImg.png" />
						</u-image>
						<view>
							<view class="divName">{{ '菜名：'+item.name }}</view>
							<view class="divDesc">{{ '介绍：'+item.description }}</view>
							<view class="divDesc">{{ '月销：' + (item.saleNum ? item.saleNum : 0) }}</view>
							<view class="divBottom">
								<text>￥</text>
								<text>{{ item.price / 100 }}</text>
							</view>
							<view class="divNum">
								<view class="divAdd" v-if="item.number >= 1">
									<image src="../../static/images/subtract.png"
										@click.prevent.stop="subtractCart(item)" />
								</view>
								<view class="divDishNum">{{ item.number }}</view>
								<view class="divTypes" v-if="item.flavors && item.flavors.length > 0 && !item.number"
									@click.prevent.stop="chooseFlavorClick()">选择规格</view>
								<view class="divAdd" v-else>
									<image src="../../static/images/add.png" @click.prevent.stop="addCart(item,$event)"></image> 
								
								</view>
							</view>
						</view>
						
						<!-- 点击element组件 -->
						<view class="shuju" @click="dataDetail(index)">数据推荐</view>
					</view>
	
				<!-- </mescroll-uni> -->
				<view class="space_scroll-view">
				</view>
				</scroll-view>
			</view>
		</view>
		
		
		<!-- 菜品详情弹窗 -->
		<u-popup @close="dishclose" :closeOnClickOverlay="true" :round="10" mode="center" :show="detailsDialog.show"
			 ref="detailsDialog">
			<view class="detailsDialog">
				<view class="divContainer">
					<u-image :src="detailsDialog.item.image">
						<view slot="error" class="image-slot">
							<image src="../../static/images/noImg.png" />
						</view>
					</u-image>
					<view class="title">{{ detailsDialog.item.name }}</view>
					<view class="content">{{ detailsDialog.item.description }}</view>
				</view>
				<view class="divNum">
					<view class="left">
						<text>￥</text>
						<text>{{ detailsDialog.item.price / 100 }}</text>
					</view>
					<view class="right">
						<view class="divSubtract" v-if="detailsDialog.item.number > 0">
							<image src="../../static/images/subtract.png" @click="subtractCart(detailsDialog.item)" />
						</view>
						<view class="divDishNum">{{detailsDialog.item.number == null ? "" : detailsDialog.item.number}}</view>
						<view class="divTypes"
							v-if="detailsDialog.item.flavors && detailsDialog.item.flavors.length > 0 && !detailsDialog.item.number"
							@click="chooseFlavorClick(detailsDialog.item)">
							选择规格
						</view>
						<view class="divAdd" v-else>
							<image src="../../static/images/add.png" @click="addCart(detailsDialog.item,$event)" />
						</view>
					</view>
				</view>
				<!-- <view class="detailsDialogClose" @click="detailsDialog.show = false">
					            <image  src="../../static/images/close.png"/>
					          </view> -->
			</view>
		
			<!-- </u-modal> -->
		</u-popup>
		
		
		
		<!-- 数据表弹窗 -->
		<u-popup @close="dishclosed" :closeOnClickOverlay="true" :round="10" mode="center" zoom="true" :show="datashow">
			<view class="chart1">
			<view class="chart2">
				
			    <qiun-data-charts 
			      type="line"
			      :opts="optsd"
			      :chartData="chartDatad"
			    />
				</view>
			
			</view>
		</u-popup>
		
		
		
		
		
		
		
		
	
	
		<!-- 组件 -->
		<!-- <tips ref="tips"></tips> -->
		<view class="order-on" v-show="modaishow">
			<image src="/static/index_image/null.png" mode="widthFix"></image>
			<view>{{tips}}</view>
		</view>
		
		
	
	</view>
</template>

<script>
	import {
		cartListApi,
		categoryListApi,
		dishListApi,
		setmealListApi,
		clearCartApi,
		updateCartApi,
		setMealDishDetailsApi,
		addCartApi
	} from '../../api/index';
	import tips from '../../components/stips/tips.vue';
	export default{
		components:{
			tips
		},
		data(){
		return{
			//词云属性数据
			chartData: {},
			opts: {
			        color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
			        padding: undefined,
			        enableScroll: false,
			        extra: {
			          word: {
			            type: "normal",
			            autoColors: false
			          }
			        }
			      },
			chartDatad: {},
			      //您可以通过修改 config-ucharts.js 文件中下标为 ['line'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
			optsd: {
			        color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
			        padding: [15,10,0,15],
			        enableScroll: false,
			        legend: {},
			        xAxis: {
			          disableGrid: true,
					  axisLabel: {
						  textStyle: {
						        fontSize:'5',
						}
					  }
			        },
			        yAxis: {
			          gridType: "dash",
			          dashLength: 2
			        },
			        extra: {
			          line: {
			            type: "straight",
			            width: 2,
			            activeType: "hollow"
			          }
			        }
			      },
			
			
			//搜索关键词
			searchdata:'',
			categoryId:undefined,
			dishList:[],
			searchResult: [{image:"/static/menu/redmeat.jpg",name:"红烧肉",description:"非常好吃，香辣可口",flavors:["麻辣","微辣"],saleNum:55,price:2500,number:1},
			 {image:"/static/menu/laziji.jpg",name:"辣子鸡",description:"爆香麻辣，入味十足",flavors:["麻辣","微辣"],saleNum:45,price:1500,number:1},
			 {image:"/static/menu/jianjiaoji.jpeg",name:"尖椒鸡",description:"麻辣可口",flavors:["麻辣","微辣"],saleNum:45,price:3500,number:1},
			 {image:"/static/menu/tudourousi.jpg",name:"土豆肉丝",description:"酸甜可口，好吃到爆",flavors:["麻辣","微辣"],saleNum:45,price:3500,number:1},
			 {image:"/static/menu/xiaochaorou.jpg",name:"小炒肉",description:"葱香美味，令人回味",flavors:["麻辣","微辣"],saleNum:75,price:2500,number:1},
			 // {image:"/static/menu/ee04a05a-1230-46b6-8ad5-1a95b140fff3.png",name:"红烧肉米饭",description:"管饱",flavors:["麻辣","微辣"],saleNum:135,price:2,number:20},
			 // {image:"/static/menu/ea405212-a8e3-4e8b-a09d-ce43a067d092.jpeg",name:"白切鸡",description:"非常好吃，又嫩又脆",flavors:["麻辣","微辣"],saleNum:15,price:65,number:29},
			 // {image:"/static/menu/e5b33c12-fc71-465d-806b-a1ff38bb5d30.jpeg",name:"红烧烤乳猪",description:"娇嫩可口",flavors:["麻辣","微辣"],saleNum:85,price:35,number:27},
			 // {image:"/static/menu/e476f679-5c15-436b-87fa-8c4e9644bf33.jpeg",name:"烤肉",description:"好吃美味",flavors:["麻辣","微辣"],saleNum:95,price:45,number:26},
			 // {image:"/static/menu/d2f61d70-ac85-4529-9b74-6d9a2255c6d7.jpg",name:"水煮白菜",description:"非常营养",flavors:["麻辣","微辣"],saleNum:45,price:55,number:25},
			 // {image:"/static/menu/a0f92f2c-882b-4810-b164-9cb266b4f8bf.jpg",name:"三鲜肉炒莲白",description:"非常好吃，又补",flavors:["麻辣","微辣"],saleNum:35,price:25,number:24},
			 
			],//虚拟的查询结果,
			acomment:[],
			max:4,
			menus:false,
			setdata: [], //历史搜索
			setdataShow: false,
			detailsDialog: {
				show: false,
				item: {
					image:"",
					name:"",
					description:"",
					flavors:[],
					saleNum:undefined,
					price:undefined,
					number:undefined
				}
			},
			setMealDialog: {
				show: false,
				item: {}
			},
			tips:'',
			modaishow:false,
			visible: false,
			datashow:false,
			chiyun:true,

		}
		},
		watch:{
			searchdata:{
				handler(val){
					if(val==''){
						this.menus=false
						this.chiyun=true
					}
				}
			}
			// acomment:{
			// 	handler(val){
			// 		if(val==[]){
			// 			this.menus=false
			// 			let bull = true
			// 			let tips ='没有你要找的商品'
			// 			this.tising(bull,tips)
			// 		}
			// 	}
			// }
		},
		//搜索
		methods:{
			dishclose() {
				this.detailsDialog.show = false;
			},
			dishclosed() {
				this.datashow = false;
			},
			seArcha(){
				console.log(this.searchdata)
				let searchkey = this.searchdata
				this.searchData(searchkey)
				this.getStorage(searchkey)
			},
			onKeyInput(e){
				console.log(e.detail.value)
				let searchkey = e.detail.value
				this.searchData(searchkey)
				this.getStorage(searchkey)
			},
			searchData(searchkey){
				let data={
					searchdata:searchkey
				}
				this.acomment=this.searchResult.filter((p)=>{
				return p.name.indexOf(searchkey) !==-1 && searchkey!==''})
				
				console.log(this.acomment)
				if(this.acomment && this.acomment!==[]){
				this.menus=true
				this.modaishow = false
				this.tips ='没有你要找的商品'
				console.log(this.tips)
				}else{
						this.menus=false
						this.modaishow = true
						this.tips ='没有你要找的商品'
						console.log(this.tips)
						this.chiyun=true
				}
				if(this.menus==true || this.modaishow ==true){
					this.chiyun=false
				}
				if(searchkey==''){
					this.chiyun=true
				}
				
			},
			tising(bull,tips){
				this.$nextTick(()=>{
					this.$refs.tips.init(bull,tips)
				})
			},
			getStorage(searchkey){
				let arrary = uni.getStorageSync('search_key') || []
				arrary.unshift(searchkey)
				uni.setStorageSync('search_key',arrary)
			},
			setStorage(){
				let setdata=uni.getStorageSync('search_key')
				let setdataarry = Array.from(new Set(setdata))
				// console.log(setdataarry)
				
				if(setdataarry==''){
					this.setdataShow=false
				}else{
					this.setdata=setdataarry
					this.setdataShow=true
				}
			},
			removeStorage(){
				uni.removeStorageSync('search_key');
				this.setStorage()
			},
			menubtm(mc){
				this.searchData(mc)
				this.setdataShow=false
			},
			

			//查询菜
			async getDishList() {
				if (!this.categoryId) {
					return;
				}
				const res = await dishListApi({
					categoryId: this.categoryId,
					status: 1
				});
				if (res.code === 0) {
					let dishList = res.data;
					const cartData = this.cartData;
					if (dishList.length > 0 && cartData.length > 0) {
						dishList.forEach(dish => {
							cartData.forEach(cart => {
								if (dish.id === cart.dishId) {
									dish.number = cart.number;
								}
							});
						});
					}
					this.dishList = dishList;
				} else {
					return uni.$showMsg(res.msg == 'token不能为空'? '未登录' : res.msg);;
				}
			},
			//菜详情页面
			dishDetails(item) {
				//先清除对象数据，如果不行的话dialog使用v-if
				this.detailsDialog.item = {};
				this.setMealDialog.item = {};
				if (Array.isArray(item.flavors)) {
					this.detailsDialog.item = item;
					console.log('item',item)
					this.detailsDialog.show = true;
				} },
			dataDetail(item) {
					//先清除对象数据，如果不行的话dialog使用v-if
					if (item !=-1) {
						console.log('item',item)
						this.getServerDatad(item)
						this.datashow = true;
					} },
				
			// async dishDetails(item) {
			// 	//先清除对象数据，如果不行的话dialog使用v-if
			// 	this.detailsDialog.item = {};
			// 	this.setMealDialog.item = {};
			// 	if (Array.isArray(item.flavors)) {
			// 		this.detailsDialog.item = item;
			// 		console.log('item',item)
			// 		this.detailsDialog.show = true;
			// 	} 
			// 	// else {
			// 	// 	//显示套餐的数据
			// 	// 	const res = await setMealDishDetailsApi(item.id);
			// 	// 	if (res.code === 0) {
			// 	// 		this.setMealDialog.item = {
			// 	// 			...item,
			// 	// 			list: res.data
			// 	// 		};
			// 	// 		this.setMealDialog.show = true;
			// 	// 	} else {
			// 	// 		return uni.$showMsg(res.msg == 'token不能为空'? '未登录' : res.msg);;
			// 	// 	}
			// 	// }
			// },
			// 获取 Token 信息
			getTokenInfo() {
			    const token = uni.getStorageSync('token');
			    if (!token) {
			        uni.showModal({
			            title: '提示',
			            content: '请登录',
			            success: function(res) {
			                if (res.confirm) {
			                    uni.switchTab({
			                        url: '/pages/my/my'
			                    });
			                } else if (res.cancel) {
			                    console.log('用户点击取消');
			                }
			            }
			        });
			        return;
			    }
			    return token;
			},
			//菜单中往购物车中添加商品
			async addCart(item,event) {
				const token = this.getTokenInfo();
				if (!token) return;
				
				let params = {
					amount: item.price / 100, //金额
					dishFlavor: item.dishFlavor, //口味  如果没有传undefined
					dishId: undefined, //菜品id
					setmealId: undefined, //套餐id
					name: item.name,
					image: item.image
				};
				if (Array.isArray(item.flavors)) {
					//表示是菜品
					params.dishId = item.id;
				} else {
					//表示套餐 套餐没有口味
					params.setmealId = item.id;
				}
				const res = await addCartApi(params);
				if (res.code === 0) {
					this.dishList.forEach(dish => {
						if (dish.id === item.id) {
							console.log('数量={}', res.data.number);
							dish.number = res.data.number;
						}
					});
					if (this.setMealDialog.show) {
						console.log(res.data.number);
						item.number = res.data.number;
					}
					this.getCartData();
				} else {
					return uni.$showMsg(res.msg == 'token不能为空'? '未登录' : res.msg);;
				}
			},
			
			
			
			//得到搜索词云数据
			getServerData() {
			      //模拟从服务器获取数据时的延时
			      setTimeout(() => {
			        //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
			        let res = {
			            series: [
			              {
			                name: "红烧肉",
			                textSize: 25,
			                data: undefined
			              },
			              {
			                name: "辣子鸡",
			                textSize: 20,
			                data: undefined
			              },
			              {
			                name: "家常菜",
			                textSize: 20,
			                data: undefined
			              },
			              {
			                name: "烧烤",
			                textSize: 20,
			                data: undefined
			              },
			              {
			                name: "特色菜",
			                textSize: 20,
			                data: undefined
			              },
			              {
			                name: "干锅",
			                textSize: 20,
			                data: undefined
			              },
			              {
			                name: "汤菜",
			                textSize: 20,
			                data: undefined
			              },
			              {
			                name: "盖饭",
			                textSize: 20,
			                data: undefined
			              },
			              {
			                name: "饮料",
			                textSize: 10,
			                data: undefined
			              },
			              {
			                name: "米饭",
			                textSize: 12,
			                data: undefined
			              },
			              {
			                name: "回锅肉",
			                textSize: 10,
			                data: undefined
			              },
			              {
			                name: "鱼香肉丝",
			                textSize: 12,
			                data: undefined
			              },
			              {
			                name: "干锅鸡",
			                textSize: 10,
			                data: undefined
			              },
			              {
			                name: "剁椒鲫鱼",
			                textSize: 12,
			                data: undefined
			              },
			              {
			                name: "盐煎肉",
			                textSize: 10,
			                data: undefined
			              },
			              {
			                name: "豆干肉丝",
			                textSize: 12,
			                data: undefined
			              }
			            ]
			          };
			        this.chartData = JSON.parse(JSON.stringify(res));
			      }, 500);
			    },
			
			//得到菜品销量表数据
			getServerDatad(index) {
			      //模拟从服务器获取数据时的延时
				  //生产各个表最大值与最小值
				  let max = this.getRandomNumber(this.acomment.length,200,140)
				  let min = this.getRandomNumber(this.acomment.length,100,70)
				  let kmax = this.getRandomNumber(this.acomment.length,100,80)
				  let kmin = this.getRandomNumber(this.acomment.length,40,30)
				  let pmax = this.getRandomNumber(this.acomment.length,50,30)
				  let pmin = this.getRandomNumber(this.acomment.length,30,20)
				  //通过最值生产用于图表的数据
				  let mnum = this.getRandomNumber(6,max[index],min[index])
				  let exnum = this.getRandomNumber(6,kmax[index],kmin[index])
				  let price = this.getRandomNumber(6,pmax[index],pmin[index])
				  
			      setTimeout(() => {
			        //模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
			        let res = {
			            categories: ["1月","2月","3月","4月","5月","6月"],
			            series: [
			              {
			                name: "出餐销量",
			                data: mnum
			              },
			              {
			                name: "备菜库存",
			                data: exnum
			              },
			              {
			                name: "价格浮动",
			                data: price
			              }
			            ]
			          };
			        this.chartDatad = JSON.parse(JSON.stringify(res));
			      }, 500);
			    },
				
				
			// 指定范围内，指定个数，无重复的随机整数
			getRandomNumber(n,min,max){
			    let arr=[];
			    for(let i = 0; i < n; i ++){
			        arr[i] = parseInt(Math.random() * (max - min + 1) + min);
			    }
			    // for(let i = 0; i < n; i++){
			    //     for(let j = i + 1; j < n; j ++){
			    //         if(arr[i] === arr[j]){
			    //             this.getRandomNumber(n,min,max);
			    //             return false;
			    //         }
			    //     }
			    // }
			    return arr
			},

				
				
			
			
			//方法最后
		},
		
		
		
		
		
		
		created(){
			this.setStorage()
		},
		onReady() {
		    this.getServerData();
		  },
		
		
	}
</script>

<style scoped>
	/* 结果样式 */
	@import url('/pages/index/index.css');
	.divBody .divMenu .mescro-uni{
		 height: calc(100vh - var(--height));
	 }
	 .divBody .divMenu .divItem > view {
	   position: relative;
	   margin: auto;
	 }
	 .divBody .divMenu .divItem .shuju{
		 border: 10upx #fff127 solid;
		 background-color: #fff127;
	 }
	 
	 /* 搜索样式 */
	.content-left{margin:0 20upx;}
	.search{
		height: 70upx;
		line-height: 70upx;
		width: 100%;
		display: flex;
		flex-direction: row;
		background: #f8f8f8;
		margin-left: 20upx;
	}
	.search input{
		height: 70upx;
		line-height: 70upx;
		width: 100%;
		font-size: 30upx;
		color: #666666;
		padding-left: 30upx;
		border: #000000 30upx;
	}
	.search-cont{display: flex;justify-content: space-between;height: 70upx;align-items: center;
	padding: 30upx 0;}
	.search-code{
		width: 150upx;height: 50upx;text-align: center;font-size: 30upx;border: #20232A;
	}
	.search-history{margin: 20upx;}
	.search-title{font-size: 30upx;font-weight: bold;
		display: flex;justify-content: space-between;
		align-items: center;
		height: 60upx;
		line-height: 60upx;
	}
	
	.search-title image{width: 36upx;height: 36upx;display: block;}
	.menu-block view{
		background: #f7f8fa;
		border-radius: 6upx;
		font-size: 27upx;
		color: #292c33;
		text-align: center;
		padding: 10upx;
		margin: 20upx 20upx 0 0;
	}
	.menu-block{
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		flex-wrap: wrap;
	}
	.order-on{width:400upx;height:400upx;
	margin: 90upx auto 0 auto;
	text-align: center;
	font-size: 28upx;
	}
	.order-on image{
		display: block;
		 width: 250upx;height: 250upx;
		 margin:0 auto;
		 padding-bottom: 30upx;
	}
	
	 /* 词云样式 */
	.charts-box{
	    width: 100%;
	    height: 300px;
	  }
	.charts-box view{
		  height: 70upx;
		  line-height: 70upx;
		  width: 100%;
		  font-size: 30upx;
		  color: #666666;
		  text-align: center;
		  
	  }
	.chart1 .charts-box1{
	      width: 100%;
	      height: 200upx;
	    }
	.chart1{
		
	  display: flex;
	  flex-direction: column;
	  text-align: center;
	}
	
	
</style>
